# 模型文件
from datetime import datetime
from exts import db

# 用户
class User(db.Model):
    __tablename__ = 'user_py'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), nullable=False)
    password = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(64), unique=True, nullable=False)
    join_time = db.Column(db.DateTime, default=datetime.now)

# 问题
class Question(db.Model):
    __tablename__ = 'question'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(256), nullable=False)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)
    # 外键，关联user表的id
    author_id = db.Column(db.Integer, db.ForeignKey('user_py.id'))
    # user 表的反向引用
    author = db.relationship(User, backref='questions')

# 答案
class Answer(db.Model):
    __tablename__ = 'answer'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)
    # 外键
    author_id = db.Column(db.Integer, db.ForeignKey('user_py.id'))
    question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
    # 关系
    author = db.relationship(User, backref='answers') # 回答问题的用户
    # 回答列表按照创建时间降序排列
    question = db.relationship(Question, backref=db.backref('answers', order_by=create_time.desc()))